define(function(require,exports,module){
	require("resource/js/easyui/themes/icon.css");
	require("resource/js/easyui/easyloader.js");
	require.async("resource/js/component/rules.js");
	var A = require("resource/js/component/ajax.js");
	var C = require("resource/js/config/const.js");
	var easyutil = require("resource/js/component/easyutil.js");
	var treeutil = require("resource/js/component/treeutil.js");
	var easycombobox = require("resource/js/component/easycombobox.js");

	var arr = [];
	easycombobox.create({
		url:BASEPATH+"/base/authoriza/basecode/getType.htm",
		param:{checkeds:"roller_type,process_state,com_status"}  
	});
	//弹出加载层
	function load() {
		$("<div class=\"datagrid-mask\"></div>").css({
			display: "block",
			width: "100%",
			height: $(window).height()
		}).appendTo("body");
		$("<div class=\"datagrid-mask-msg\"></div>").html("保存中，请稍候。。。").appendTo("body").css({
			display: "block",
			left: ($(document.body).outerWidth(true) - 190) / 2,
			top: ($(window).height() - 45) / 2
		});
		setTimeout(disLoad, 3000);
	}
    //取消加载层
	function disLoad() {
		$(".datagrid-mask").remove();
		$(".datagrid-mask-msg").remove();
	}

	function MatchInt(){
		using(["validatebox"],function(){
			$.extend($.fn.validatebox.defaults.rules, {    
			    matchInt: {    
			        validator: function(value){    
			        	return /^[1-9]*[1-9][0-9]*$/.test(value);
			        },    
			        message: "输入必须为正整数"  
			    }
			});
		});
	}
	
	using(["validatebox"],function(){
		$.extend($.fn.validatebox.defaults.rules, {    
		    matchMax: {    
			validator: function(value){    
				return value <= 1 & value > 0;
			},    
			message: "输入折扣不能超过1且不小于0"  
		    }
		});
	});
	/**
	 * 服务类型
	 */
	function getBenifitType(type){
		easyutil.ajaxHandler(BASEPATH+'/home/benifit/queryBenifitType.htm',null,function(code,msg,data){
			easycombobox.init({ ele:"#benType"+type,valueField:'id',textField:'name',onChange:function(newValue,oldValue){
				
				if($.inArray(newValue,arr) != -1){
					$(".tr_discount_"+type).show();
					$("#discount_"+type).numberbox('setValue','');
					$("#couponType"+type).combobox('setValue','0');
					$("#nums_"+type).numberbox('setValue','');
				} else {
					$(".tr_discount_"+type).hide();
					$("#discount_"+type).numberbox('setValue','');
					$("#couponType"+type).combobox('setValue','1');
					$("#nums_"+type).numberbox('setValue','');
				}
			}}).load(data);
		});
	}
	
	var config={
			type:"process",
			name:"水稳摊铺压实工艺",
			column:[[
				{field:'pavingId',title:'摊铺工艺Id',width:70,align:'center',height:50,hidden:true},
		        {field:'layerName',title:'摊铺层级',width:90,align:'center',height:50},
		        {field:'processVersion',title:'工艺版本',width:50,align:'center',height:50},
		        {field:'minSpeed',title:'速度范围（m/min）',width:50,align:'center',height:50,formatter:function(value,row,index){
		        	return row.minSpeed+'~'+row.maxSpeed;
		        }},
		        {field:'startTime',title:'开始时间',width:50,align:'center',height:50},
		        {field:'endTime',title:'结束时间',width:50,align:'center',height:50}
		        ]
			]
	}
		
	
	var dgutil = undefined;
	var datagridconfig = undefined;
	function initPage(){
		var sectionId = sessionStorage.getItem('sectionId');  //获取标段id
		if(sectionId == null){
			sectionId = 0;
		}
		$("#searchSectionId").val(sectionId);
		dgutil=new easyutil.ajaxDataGrid(datagridconfig);

		//easycombobox.init({ ele:"#searchStatus",prompt:'请选择可用状态', grouptype:"startType",value:'0'});
		/*A.init().success(function(c,m,d){
			if(d){
				$.each(d,function(i,n){
					arr.push(n.typeId);
				})
			}
		}).error(function(c,m,d){
			$.messager.show({title:'系统提示',msg:m,timeout:5000,showType:'slide'});
		}).post(BASEPATH+"/home/benifit/queryLongBenifit.htm");*/
		
	}
	
	
	var checkDate = function(type){
		var stime = $("#startTime"+type).datebox('getValue');
		var etime = $("#endTime"+type).datebox('getValue');
		
		if(Date.parse(etime) < Date.parse(stime)){
			$.messager.show({title:'系统提示',msg:'结束时间不能小于开始时间',timeout:5000,showType:'slide'});
			return false;
		}
		
		return true;
	}
	
	//删除
	var delInit=function(baseUrl,rows){
		var checks="";
		
		for(var key in rows){
			if(key==rows.length-1){
				checks+=rows[key].pavingId;
			}else{
				checks+=rows[key].pavingId+",";
			}
		}
		easyutil.ajaxHandler(baseUrl,{checkeds:checks},function(){
			dgutil.delRow(rows);
		});
	}
	
	var initComb = function(type){
		var arr = ['init','rep','final'];
		for(var i = 0; i < arr.length; i ++){
			easycombobox.init({ ele:"#"+arr[i]+"_roller_type"+type,prompt:'', grouptype:"roller_type"});
			easycombobox.init({ ele:"#"+arr[i]+"_status"+type,prompt:'', grouptype:"com_status"});
		}
		easycombobox.init({ ele:"#"+"state"+type,prompt:'', grouptype:"process_state"});
	}
	
	function initLayerAndMaterial(pid, cid, row) {
		/**
		 * 一级
		 */
		A.init().sync().success(function(code,msg,data){
			easycombobox.init({
				ele: "#"+pid,
				valueField: 'id',
				remote: false,
				textField: 'name',
				prompt: '请选择',
				onChange: function(rec) {
					$("#"+cid).combobox("clear");
					A.init().sync().success(function(code,msg,data){
						easycombobox.init({
							ele: "#"+cid,
							valueField: 'id',
							remote: false,
							textField: 'name',
							prompt: '请选择'
							
						}).load(data);
					}).post(BASEPATH + '/base/authoriza/conmonData/queryDataNoCache.htm', {
						queryId: 'getDcsMaterial',
						param:  $("#"+pid).combobox("getValue")
					});
				}
			}).load(data);
		}).error(function(code,msg,data){
			$.messager.alert("系统提示", msg, "error");
		}).post(BASEPATH+'/base/authoriza/conmonData/queryDataNoCache.htm',{"queryId":"getDcsLayer"});

		/**
		 * 二级
		 */
		A.init().sync().success(function(code,msg,data){
			easycombobox.init({
				ele: "#"+cid,
				valueField: 'id',
				remote: false,
				textField: 'name',
				prompt: '请选择',
				onChange: function(rec) {
					
				}
			}).load(data);
		}).post(BASEPATH + '/base/authoriza/conmonData/queryDataNoCache.htm', {
			queryId: 'baseareaparam',
			param:  $("#"+pid).combobox("getValue")
		});
		if (row && row.layerId) {
			$("#"+pid).combobox("setValue", row.layerId);
		}
		if (row && row.materialId) {
			$("#"+cid).combobox("setValue", row.materialId);
		}
	}
	//修改
	var updDialogInit=function(baseUrl,row){
		
		$("#adddlg").dialog({
			iconCls:'icon-save',
			title:config.name+'修改',
			href:baseUrl,
			//width: 430,
			//height: 350,
			onLoad:function(){
				
				initLayerAndMaterial('layerId_Upd','materialId_Upd');
				initComb('_Upd');
				
				var process = JSON.parse(row.processJson);
				
				row.init_roller_type = process.init_roller_type;
				row.init_status = process.init_status;
				row.init_min_compation = process.init_min_compation;
				row.init_max_compation = process.init_max_compation;
				row.init_min_speed = process.init_min_speed;
				row.init_max_speed = process.init_max_speed;

				row.rep_roller_type = process.rep_roller_type;
				row.rep_status = process.rep_status;
				row.rep_min_compation = process.rep_min_compation;
				row.rep_max_compation = process.rep_max_compation;
				row.rep_min_speed = process.rep_min_speed;
				row.rep_max_speed = process.rep_max_speed;

				row.final_roller_type = process.final_roller_type;
				row.final_status = process.final_status;
				row.final_min_compation = process.final_min_compation;
				row.final_max_compation = process.final_max_compation;
				row.final_min_speed = process.final_min_speed;
				row.final_max_speed = process.final_max_speed;
				
				$('#updform').form('load',row);
				
				$("#token_Id_upd").val(getRandom());
			},
			
			buttons:[{
				text:'保存',
				iconCls:'icon-ok',
				accessKey:{akey:18,mkey:83},
				handler:function(){
					using(["form"],function(){
						if($("#updform").form("validate")){
							load();
							if(!checkDate('_Upd')){
								return;
							}
							
							var obj = $("#updform").serializeJson();
							obj = processData(obj);
							
							/**
							 * 处理标段Id
							 */
							var sectionId = sessionStorage.getItem('sectionId');
							if(sectionId == null || sectionId == undefined){
								sectionId = '001';
							}
							obj.sectionId = sectionId;
							obj.processType = '01';
							
							// easyutil.ajaxHandler(BASEPATH+"/dcs/process/updatePavingProcessModel.htm",obj,function(){
							// 	dgutil.pager();
							// 	$("#adddlg").dialog("close");
							// });
							$.ajax({
								type: 'POST',
								url: BASEPATH+"/dcs/process/updatePavingProcessModel.htm",
								data: obj,
								dataType: 'json',
								beforeSend: function () {
									// $("#adddlg").dialog("close");
									// alert("hao");
									load();
								},
								complete: function () {
									disLoad();
								},
								success: function (data) {
									disLoad();
									dgutil.pager();
									// location.reload();
									// location.replace(location.href);
									if(data.msg.length > 0){
										$.messager.show({title:C.MESSAGE.MSGTITLE,msg:data.msg});
									}
									$("#adddlg").dialog("close");
								}
							});
						}
					});
				}
				},{
					text:'取消',
					addClass:'l-btn-red',iconCls:'icon-not',
					accessKey:{akey:18,mkey:67},
					handler:function(){
						$("#adddlg").dialog("close");
					}
				}]
				
				
			});
		$("#adddlg").dialog("open");
	}
	
	var processData = function(obj){
		var process = {};
		process.init_roller_type = obj.init_roller_type;
		process.init_status = obj.init_status;
		process.init_min_compation = obj.init_min_compation;
		process.init_max_compation = obj.init_max_compation;
		process.init_min_speed = obj.init_min_speed;
		process.init_max_speed = obj.init_max_speed;
		
		process.rep_roller_type = obj.rep_roller_type;
		process.rep_status = obj.rep_status;
		process.rep_min_compation = obj.rep_min_compation;
		process.rep_max_compation = obj.rep_max_compation;
		process.rep_min_speed = obj.rep_min_speed;
		process.rep_max_speed = obj.rep_max_speed;
		
		process.final_roller_type = obj.final_roller_type;
		process.final_status = obj.final_status;
		process.final_min_compation = obj.final_min_compation;
		process.final_max_compation = obj.final_max_compation;
		process.final_min_speed = obj.final_min_speed;
		process.final_max_speed = obj.final_max_speed;
		
		var array = ['init','rep','final'];
		for(var i = 0; i < array.length; i ++){
			delete obj['' + array[i] + '_roller_type' +''];
			delete obj['' + array[i] + '_status' +''];
			delete obj['' + array[i] + '_min_compation' +''];
			delete obj['' + array[i] + '_max_compation' +''];
			delete obj['' + array[i] + '_min_speed' +''];
			delete obj['' + array[i] + '_max_speed' +''];
		}
		obj.processJson = JSON.stringify(process);
		return obj;
	}
	
	var checkType = function(obj,arr,type){
		if($.inArray(obj.benType,arr) == -1){//短期
			//delete obj.discount;
			if($("#couponType"+type).combobox('getValue') == '0'){//长期
				$.messager.show({title:'系统提示',msg:'服务类型与优惠券类型不匹配，请重新选择',timeout:5000,showType:'slide'});
				return false;
			}
		}
		
		//var nums = $("#nums_"+type).numberbox('getValue');
		if($.inArray(obj.benType,arr) != -1){//长期
			if($("#couponType"+type).combobox('getValue') == '1'){//短期
				$.messager.show({title:'系统提示',msg:'服务类型与优惠券类型不匹配，请重新选择',timeout:5000,showType:'slide'});
				return false;
			}
			if(obj.discount == undefined || obj.discount == ''){
				$.messager.show({title:'系统提示',msg:'该新添优惠券为折扣券，请填写优惠折扣',timeout:5000,showType:'slide'});
				return false;
			}
			if(obj.nums == undefined || obj.nums == ''){
				$.messager.show({title:'系统提示',msg:'该新添优惠券为折扣券，请填写发放数量',timeout:5000,showType:'slide'});
				return false;
			}
		}
		
		return true;
	}


	var getRandom = function(){
		var hostName = window.location.hostname;
		if(hostName == 'localhost'){
			hostName = '127.0.0.1';
		}
		return hostName.replace(/\./g,'')+(new Date().getTime())+Math.round(Math.random()*10000);
	}

	//增加
	var addDialogInit=function(baseUrl,row){
		$("#adddlg").dialog({
			iconCls:"icon-save",
			title:config.name+"增加",
			href:baseUrl,
			modal:true,
			onLoad:function(){
				initLayerAndMaterial('layerId_Add','materialId_Add');
				initComb('_Add');
				$('#token_Id_add').val(getRandom());
			},
			buttons:[{
					text:"保存",
					iconCls:"icon-ok",
					accessKey:{akey:18,mkey:83},
					handler:function(){
						using("form",function(){
							if($("#addform").form("validate")){
								load();
								if(!checkDate('_Add')){
									return;
								}
								
								var obj = $("#addform").serializeJson();
								
								
								obj = processData(obj);
								
								/**
								 * 处理标段Id
								 */
								var sectionId = sessionStorage.getItem('sectionId');
								if(sectionId == null || sectionId == undefined){
									sectionId = '001';
								}
								obj.sectionId = sectionId;
								obj.processType = '01';


								// easyutil.ajaxHandler(BASEPATH+"/dcs/process/savePavingProcessModel.htm",obj,function(){
								// 	dgutil.pager();
								// 	$("#adddlg").dialog("close");
								// });

								$.ajax({
									type: 'POST',
									url: BASEPATH+"/dcs/process/savePavingProcessModel.htm",
									data: obj,
									dataType: 'json',
									beforeSend: function () {
										// $("#adddlg").dialog("close");
										// alert("hao");
										load();
									},
									complete: function () {
										disLoad();
									},
									success: function (data) {
										disLoad();
										dgutil.pager();
										if(data.msg.length > 0){
											$.messager.show({title:C.MESSAGE.MSGTITLE,msg:data.msg});
										}
										$("#adddlg").dialog("close");
									}
								});
							}
						});
					}
					},
					{
						text:'取消',
						addClass:'l-btn-red',iconCls:'icon-not',
						accessKey:{akey:18,mkey:67},
						handler:function(){
							$("#adddlg").dialog("close");
						}
					}
			]
		});
		$("#adddlg").dialog("open");
	}
	

    exports.trans = function(){
    	var buttons={
			title:{
				_class:"",
				text:"水稳工艺列表"
				
			},
			btn:[/*{
					 iconCls:"icon-search",
					 text:"查询",
					 addClass:"l-btn-display",
					 url:"/dcs/process/queryPavingProcessByPage.htm",
					 handler:function(){
						 dgutil.pager(1);
					 }
			     },*/
			     {
			    	iconCls:"icon-add",
			    	text:"添加",
			    	addClass:"l-btn-display",
			    	url:"/view/dcs/pavingprocess/add",
			    	handler:addDialogInit
			     },
			     {
			    	 iconCls:"icon-edit",
				     text:"修改",
				     addClass:"l-btn-display",
				     url:"/view/dcs/pavingprocess/upd",
				     needRow:true,
				     handler:updDialogInit
			     },
			     {
		    	 	iconCls: 'icon-remove',
					url:'/dcs/process/deletePavingProcess.htm',
					text:"删除",
					addClass:'l-btn-display',
					needRows:true,
					isCheck:true,
					handler: delInit
			     }
			     ]};
				datagridconfig={
					fitColumns:true,
					singleSelect:false,
					striped:true,
					autoRowHeight:false,
					fit:true,
					url:BASEPATH+"/dcs/process/queryPavingProcessByPage.htm",
					toolbar:buttons,
					columns:config.column,
					eid:"dg",
					args:"searchform"
				};
				using(["datagrid","parser","textbox","numberbox","dialog","combobox","datetimebox","validatebox","messager"],function(){
					initPage();
				});
	}
});


